import type { ComputedRef } from 'vue';
import { ref, onUnmounted, unref, computed } from 'vue';
import { isProdMode } from '@/utils/env';

import type { AdTableProps } from '../types/adTable';
import type { AdSearchFormProps } from '../types/adSearchForm';
import { AdSearchFormActionType } from '../types/adSearchForm';
import { AdColumn } from '../types/adTable';

import { FilterGroup } from '#/request';

export function useAdSearchForm(
  propsRef: ComputedRef<AdTableProps>,
  getLoading: ComputedRef<boolean | undefined>,
) {
  const formRef = ref<Nullable<AdSearchFormActionType>>(null);

  /** 注册 */
  function register(instance: AdSearchFormActionType) {
    isProdMode() &&
      onUnmounted(() => {
        formRef.value = null;
      });
    if (isProdMode() && instance === unref(formRef)) return;

    formRef.value = instance;
  }

  /** 方法 */
  const methods: AdSearchFormActionType = {
    /** 获取搜索信息 */
    getSearchInfo: () => {
      return unref(formRef)?.getSearchInfo() as FilterGroup;
    },
  };

  /** 搜索窗体属性 */
  const getSearchFormProps = computed((): Partial<AdSearchFormProps> => {
    const { formConfig, searchFormAutoSubmitOnEnter, searchFormSubmitOnReset, columns } =
      unref(propsRef);
    const { submitButtonOptions } = formConfig || {};
    return {
      ...formConfig,
      submitButtonOptions: { loading: unref(getLoading), ...submitButtonOptions },
      compact: true,
      autoSubmitOnEnter: searchFormAutoSubmitOnEnter,
      submitOnReset: searchFormSubmitOnReset,
      columns: columns
        ? (columns.filter(function (item) {
            //!调用filter方法，传入函数，若函数返回值为真，则返回该项，数组列不允许设置搜索
            // // console.log(index);
            return item?.filterable === true && item?.dataType !== 'array';
          }) as AdColumn[])
        : [],
    };
  });

  return { getSearchFormProps, register, methods };
}
